package relu.fbs.xt;

import relu.fbs.*;
import relu.fbs.xt.FBS8387DataReader.FileType;
import relu.fbs.xt.FBSCropData.FBSCDatum;
import relu.fbs.xt.FBSFarmData.FBSFarmDatum;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public abstract class AbstractMultipleFileDataReader {
	

//	protected abstract Map<Integer,FBSFarmData> generateFarms(String file,int yrcode) throws FileNotFoundException, IOException ,NumberFormatException, BadDataException;

	
	
	
	static void setDatum(Map<Integer,FBSFarmData> farms,int farmid,FBSFarmDatum dt,double value) throws BadDataException {
		if ( !farms.containsKey(farmid)){
			throw new Error("Attempt to det Datum for farm "+farmid+" but that farm does not exist yet ");
		}
		FBSFarmData farm = farms.get(farmid);
		if ( farm.hasDatum(dt)){
			throw new BadDataException("The datum "+dt+" has already been set ");
		}
		farm.putFarmData(dt, value);
	}
	static void setCheckedDatum(Map<Integer,FBSFarmData> farms,int farmid,FBSFarmDatum dt,double value) throws BadDataException {
		if ( !farms.containsKey(farmid)){
			throw new Error("Attempt to det Datum for farm "+farmid+" but that farm does not exist yet ");
		}
		FBSFarmData farm = farms.get(farmid);
		if ( farm.hasDatum(dt)){
			double diff=farm.getFarmDatum(dt)-value;
			if ( Math.abs(diff) > 1.0 ){
				throw new Error(farmid+" New "+dt+" with value "+value+" differs from original "+farm.getFarmDatum(dt));
			}
		}
		farm.putCheckedFarmData(dt, value);
	}
	




	
	protected static void addLabourData(String fileName,Map<Integer,FBSFarmData> farms,int yrcode) throws FileNotFoundException, IOException ,NumberFormatException,BadDataException {
		FileReader reader=new FileReader(fileName);
		BufferedReader buffrd=new BufferedReader(reader);

		String line = buffrd.readLine(); // Read the header 
		line=buffrd.readLine();
		while( line!=null){
			String[] colStrings=line.split("\t");
			int ycode=Integer.parseInt(colStrings[2]);
			if ( ycode==yrcode){
				int farmid = Integer.parseInt(colStrings[1]);
				int bline = Integer.parseInt(colStrings[0]);
				// Don't do anything with this info yet.
				if ( bline == 19 ){ // The farmer himself
					int fdob = Integer.parseInt(colStrings[4]);
					double timeWorked= Double.parseDouble(colStrings[7]);
					setDatum(farms,farmid,FBSFarmDatum.FARMERDOB,fdob+1900);
					setDatum(farms,farmid,FBSFarmDatum.FARMERTIMEWORKED,timeWorked);
				}
			}
			
			line=buffrd.readLine();
		}
	}
	

}
